package com.zzzzzz.oms.shipment;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.Basic;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zzzzzz.core.datagrid.BaseData;
import com.zzzzzz.oms.driver.DriverDao;
import com.zzzzzz.oms.legs.Legs;
import com.zzzzzz.oms.legs.LegsDao;
import com.zzzzzz.oms.vehicle.VehicleDao;
import com.zzzzzz.plugins.shiro.I;
import com.zzzzzz.sys.platform.Platform;
import com.zzzzzz.sys.platform.PlatformDao;
import com.zzzzzz.utils.BeanValidators;
import com.zzzzzz.utils.DateTimeUtils;

@Service
public class ShipmentService {
	@Resource
	public ShipmentDao shipmentDao;
	@Resource
	public Validator validator;
	@Resource
	public PlatformDao platformDao;
	@Resource
	public LegsDao legsDao;
	@Resource
	public VehicleDao vehicleDao;
	@Resource
	public DriverDao driverDao;
	int count=0;
	String platformCd;
	String code=null;
	String code1=null;
	@Transactional
	public Long save(Shipment shipment, I i) {
		System.out.println(code+"=="+code1+"=="+count);
		shipment.setUpdDt(new Date());
		shipment.setUpdBy(i.getId());
		if (shipment.getId() == null) {
			shipment.setAddDt(new Date());
			shipment.setAddBy(i.getId());
			shipment.setPlatformId(i.getPlatformId());
			shipment.setStatus("shipmentEd");
			if(shipment.getTempShipmentId()!=null){
				List<Legs> list=legsDao.findByTempShipmentId(shipment.getTempShipmentId());
				shipment.setFtranslocationId(list.get(0).getFtranslocationId());
				shipment.setTtranslocationId(list.get(0).getTtranslocationId());
			}
			if(shipment.getVehicleId()!=null){
				shipment.setCarNo(vehicleDao.findById(shipment.getVehicleId()).getCd());
			}
			if(shipment.getDriverId()!=null){
				shipment.setDriverName(driverDao.findById(shipment.getDriverId()).getName());
				shipment.setPhone(driverDao.findById(shipment.getDriverId()).getPhone());
				shipment.setIdcard(driverDao.findById(shipment.getDriverId()).getIdcard());
			}
			Platform platform=platformDao.findById(i.getPlatformId());
			SimpleDateFormat dateformat=new SimpleDateFormat("yyyyMMdd");
			String date=dateformat.format(new Date());
			if(code1==null||!code1.equals(platform.getCd()+date)){
				code1=platform.getCd()+date;
				code=shipmentDao.findByMax(i);
			}
			if(code==null){
				String cd2=platform.getCd()+date+"0001";
				code=cd2;
				shipment.setCd(cd2);
			}else{
				if(!code.substring(0,code.length()-4).equals(platform.getCd()+date)||count==0||!platformCd.equals(code.substring(0,code.length()-12))){
					count=Integer.parseInt(code.substring(code.length()-4));
					platformCd=code.substring(0,code.length()-12);
				}
				String cd=code.substring(0,code.length()-4);
				if((platform.getCd()+date).equals(cd)){
					if(count<9){
						shipment.setCd(platform.getCd()+date+"000"+String.valueOf(count+1));
						count++;
					}else if(count>=99){
						shipment.setCd(platform.getCd()+date+"0"+String.valueOf(count+1));
						count++;
					}else{
						shipment.setCd(platform.getCd()+date+"00"+String.valueOf(count+1));
						count++;
					}
				}else{
					System.out.println("---------------");
					String cd2=platform.getCd()+date+"0001";
					code=cd2;
					count=1;
					shipment.setCd(cd2);
				}
			}		
			Long id=shipmentDao.add(shipment);
			return id;
		} else {
			shipmentDao.updById(shipment);
		}

		return (long) 1;
	}
	
	@Transactional
	public BaseData batchAdd(List<Shipment> list, I i) {
		logger.info("shipment batchAdd validate start:" + DateTimeUtils.date2Str(new Date(), DateTimeUtils.FORMAT_YYYY_MM_DD_HH_MM_SS));
		//start validate
		int errTt = 0;
		StringBuilder errMsg = new StringBuilder();
		for (Shipment shipment : list) {
			try {
				BeanValidators.validateWithException(validator, shipment);
			} catch (ConstraintViolationException e) {
				List<String> msgList = BeanValidators.extractPropertyAndMessageAsList(e, ": ");
				for (String msg : msgList) {
					errTt++;
					errMsg.append("<br/>").append(msg);
				}
			} catch (Exception e) {
				logger.warn("", e);
				errTt++;
				errMsg.append("<br/>验证失败：").append(e.getMessage());
			}
		}
		if(errTt > 0){
			errMsg.insert(0, "共有"+errTt+"笔记录验证失败：");
			return new BaseData("101", errMsg.toString());
		}
		logger.info("shipment batchAdd validate end:" + DateTimeUtils.date2Str(new Date(), DateTimeUtils.FORMAT_YYYY_MM_DD_HH_MM_SS));
		logger.info("shipment batchAdd save start:" + DateTimeUtils.date2Str(new Date(), DateTimeUtils.FORMAT_YYYY_MM_DD_HH_MM_SS));
		//state save
		int susTt = 0;
		for (Shipment shipment : list) {
			save(shipment, i);
			susTt++;
		}
		logger.info("shipment batchAdd save end:" + DateTimeUtils.date2Str(new Date(), DateTimeUtils.FORMAT_YYYY_MM_DD_HH_MM_SS));
		return new BaseData("0", "共有"+susTt+"笔记录导入成功。");
	}

	private static final Logger logger = LoggerFactory.getLogger(Shipment.class);
}
